﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using log4net;
using BarberShop.BLL;
using System.Drawing;
using Maticsoft.Common;
using System.IO;


public class BasePage : System.Web.UI.Page
{
    ILog log = LogManager.GetLogger("MyLogger");
    public string UpdateFileUrl
    {
        get { return Maticsoft.Common.ConfigHelper.GetConfigString("UpdateUrl"); }
    }
    public BasePage()
    {

    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        //CancelFormControlEnterKey(this.Page.Form.Controls); //取消页面文本框的enter key
    }

    /// <summary>
    /// 应用程序路径 
    /// </summary>
    public string ApplicationPath
    {
        get
        {
            string path = HttpContext.Current.Request.ApplicationPath.ToString();
            if (path.Trim() != "/") // 判断路径是否为“/”
            {
                path += "/";
            }
            return path;
        }
    }

    /// <summary>
    ///重写页面预处理事件(在页面初始化开始时引发)
    /// 验证用户是否登录
    /// </summary>
    /// <param name="e"></param>
    protected override void OnPreInit(EventArgs e)
    {
        //if (Session["username"] == null)
        //{
        //    //string ReturnUrl=Request.Url.
        //    string url = ApplicationPath + "Default.aspx";
        //    Response.Write("<script>alert('Session过期,请重新登陆!');top.location.href='" + url + "';</script>");
        //    return;
        //}
        base.OnPreInit(e);
    }

    #region 日志处理

    ///// <summary>
    ///// 出错处理:写日志,导航到公共出错页面
    ///// </summary>
    ///// <param name="e"></param>
    //protected override void OnError(EventArgs e)
    //{
    //    Exception ex = this.Server.GetLastError();
    //    string error = this.DealException(ex);

    //    log.Error(error);
    //    if (ex.InnerException != null)
    //    {
    //        error = this.DealException(ex);
    //         log.Error(error);
    //    }
    //    this.Server.ClearError();
    //    this.Response.Redirect("/Error.aspx");
    //}

    /// <summary>
    /// 处理异常，用来将主要异常信息写入文本日志
    /// </summary>
    /// <param name="ex"></param>
    /// <returns></returns>
    private string DealException(Exception ex)
    {
        this.Application["StackTrace"] = ex.StackTrace;
        this.Application["MessageError"] = ex.Message;
        this.Application["SourceError"] = ex.Source;
        this.Application["TargetSite"] = ex.TargetSite.ToString();
        string error = string.Format("URl：{0}\n引发异常的方法：{1}\n错误信息：{2}\n错误堆栈：{3}\n",
            this.Request.RawUrl, ex.TargetSite, ex.Message, ex.StackTrace);
        return error;
    }

    #endregion

    #region 提示框,窗口
    /// <summary>
    /// MessageBox提示框
    /// </summary>
    /// <param name="Message">提示信息</param>
    public void MsgBox(string Message)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "", "<script type='text/javascript'>alert('" + Message + "');</script>");
        return;
    }

    /// <summary>
    /// MessageBox提示并转向新页面
    /// </summary>
    /// <param name="Message">提示信息</param>
    /// <param name="URL">跳转的路径</param>
    public void MsgBox(string Message, string URL)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "", "<script type='text/javascript'>alert('" + Message + "');window.location='" + URL + "';</script>");
        return;
    }
    /// <summary>
    /// 弹出新窗口
    /// </summary>
    /// <param name="pagePath">页面路径</param>
    /// <param name="winName">新窗口名称</param>
    /// <param name="winWidth">新窗口宽度</param>
    /// <param name="winHeight">新窗口高度</param>
    public void openNewWin(string pagePath, string winName, int winWidth, int winHeight)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "", "<script type='text/javascript'>window.open('" + pagePath + "','" + winName + "','toolbar=no,menubar=no,titlebar=no,directories=no,resizable=no,scroll=yes,status=no,fullscreen=no,center=yes,width=" + winWidth + ",height=" + winHeight + "');</script>");
        return;
    }

    /// <summary>
    /// 弹出模态窗口
    /// </summary>
    /// <param name="pagePath">页面路径</param>
    /// <param name="winWidth">窗口宽度</param>
    /// <param name="winHeight">窗口高度</param>
    public void openModelWin(string pagePath, int winWidth, int winHeight)
    {
        string temp;
        temp = @"<script language='javascript'>";
        temp += (@"   var sPath ='" + pagePath + "';");
        temp += (@"         strFeatures ='dialogWidth=" + winWidth + "px;dialogHeight=" + winHeight + "px;center=yes;scroll=no;help=no;status: No';");
        temp += (@"         var returnvalue = window.showModalDialog(sPath,'brower',strFeatures);");
        temp += (@"</script>");

        ClientScript.RegisterStartupScript(this.GetType(), "message", temp);
    }

    /// <summary>
    /// 弹出控制父窗口的模态窗口
    /// </summary>
    /// <param name="pagePath">页面路径</param>
    /// <param name="winWidth">窗口宽度</param>
    /// <param name="winHeight">窗口高度</param>
    /// <param name="frameshref">控制父窗口路径</param>
    public void openModelWin(string pagepath, int width, int height, string frameshref)
    {
        string temp = @"<script language='javascript'>";
        temp += (@"   var sPath ='" + pagepath + "';");
        temp += (@"         strFeatures ='dialogWidth=" + width + "px;dialogHeight=" + height + "px;center=yes;scroll=no;help=no;status=no';");
        temp += (@"         var returnvalue = window.showModalDialog(sPath,'brower',strFeatures);");
        temp += (@"         window.location.href = '" + frameshref + "';");
        temp += (@"</script>");

        ClientScript.RegisterStartupScript(this.GetType(), "message", temp);
    }

    /// <summary>
    /// 关闭本窗口
    /// </summary>
    public void CloseWin()
    {
        ClientScript.RegisterStartupScript(this.GetType(), "", "<script type='text/javascript'>window.opener=null;window.close();</script>");
        return;
    }

    /// <summary>
    /// 弹出提示信息,并关闭本窗口
    /// <param name="Words">弹出提示信息内容</param>
    /// </summary>
    public void CloseWin(string Words)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "", "<script type='text/javascript'>alert('" + Words + "');window.opener=null;window.close();</script>");
        return;
    }


    /// <summary>
    /// 关闭本窗口并,重新加载父窗口.
    /// </summary>
    /// <param name="URL">父窗口要加载的URL</param>
    public void reLoadParentAndClose(string URL)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "", "<script type='text/javascript'>window.opener.location='" + URL + "';window.close();</script>");
        return;
    }

    /// <summary>
    /// 显示提示信息,关闭本窗口并,重新加载父窗口.
    /// </summary>
    /// <param name="Words">提示消息内容</param>
    /// <param name="URL">父窗口要加载的URL</param>
    public void ShowWords_reLoadParentAndClose(string Words, string URL)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "", "<script type='text/javascript'>alert('" + Words
+ "'); window.opener.location='" + URL + "';window.close();</script>");
        return;
    }

    #endregion

    #region ip session cookies 等
    /// <summary>
    /// 获取客户端IP
    /// </summary>
    /// <returns></returns>
    public string GetClientIP()
    {
        string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (null == result || result == String.Empty)
        {
            result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }

        if (null == result || result == String.Empty)
        {
            result = HttpContext.Current.Request.UserHostAddress;
        }
        return result;
    }


    /// <summary>
    /// 获取Session值
    /// </summary>
    /// <param name="SessionID">要获取的Session值</param>
    /// <returns></returns>
    public string GetSession(string SessionID)
    {
        string restr = "unkown";
        try
        {
            restr = Session[SessionID].ToString();
        }
        catch
        {
        }
        if (restr == "unkown" && restr == null && restr == "")
        {
            Response.Redirect("/Error.aspx?Type=NoPopedom");
        }
        return restr;
    }

    /// <summary>
    /// 写Cookie
    /// </summary>
    /// <param name="CookiesName">Cookie集名称</param>
    /// <param name="name">Cookie名</param>
    /// <param name="Value">值</param>
    public void WritCookie(string CookiesName, string name, string Value)
    {
        HttpCookie cookie = new HttpCookie(CookiesName);
        cookie.Values.Add(name, Value);
        Response.AppendCookie(cookie);
    }

    /// <summary>
    /// 获取Cookie
    /// </summary>
    /// <param name="CookiesName">Cookie集名称</param>
    /// <param name="name">Cookie名</param>
    /// <param name="Value">值</param>
    public string GetCookie(string CookiesName, string name)
    {
        string value = string.Empty;
        try
        {
            HttpCookie cookie = Request.Cookies[CookiesName];
            value = cookie.Values[name];
        }
        catch
        {
            Response.Redirect("/Error.aspx?Type=GetCookie");
        }
        return value;
    }
    #endregion

    #region not use
    #region 取消页面文本控件的enter key功能

    /// <summary>
    /// 在这里我们给Form中的服务器控件添加客户端onkeydown脚步事件，防止服务器控件按下enter键直接回发
    /// </summary>
    /// <param name="controls"></param>
    public virtual void CancelFormControlEnterKey(ControlCollection controls)
    {
        //向页面注册脚本 用来取消input的enter key功能
        RegisterUndoEnterKeyScript();

        foreach (Control item in controls)
        {
            //服务器TextBox
            if (item.GetType() == typeof(System.Web.UI.WebControls.TextBox))
            {
                WebControl webControl = item as WebControl;
                webControl.Attributes.Add("onkeydown", "return forbidInputKeyDown(event)");
            }
            //html控件
            else if (item.GetType() == typeof(System.Web.UI.HtmlControls.HtmlInputText))
            {
                HtmlInputControl htmlControl = item as HtmlInputControl;
                htmlControl.Attributes.Add("onkeydown", "return forbidInputKeyDown(event)");
            }
            //用户控件
            else if (item is System.Web.UI.UserControl)
            {
                CancelFormControlEnterKey(item.Controls); //递归调用
            }
        }
    }

    /// <summary>
    /// 向页面注册forbidInputKeyDown脚本
    /// </summary>
    private void RegisterUndoEnterKeyScript()
    {
        string js = string.Empty;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("function forbidInputKeyDown(ev) {");
        sb.Append("  if (typeof (ev) != \"undefined\") {");

        sb.Append("  if (ev.keyCode || ev.which) {");
        sb.Append("   if (ev.keyCode == 13 || ev.which == 13) { return false; }");
        sb.Append("  } } }");
        js = sb.ToString();
        if (!this.Page.ClientScript.IsClientScriptBlockRegistered("forbidInput2KeyDown"))
            this.Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "forbidInput2KeyDown", js, true);
    }

    #endregion

    //#region 利用反射取/赋页面控件的值

    ///// <summary>
    ///// 从页面中取控件值，并给对象赋值
    ///// </summary>
    ///// <param name="dataType">要被赋值的对象类型</param>
    ///// <returns></returns>
    //public virtual BaseObj GetFormData(Type dataType)
    //{
    //    BaseObj data = (BaseObj)Activator.CreateInstance(dataType);//实例化一个类
    //    Type pgType = this.GetType(); //标识当前页面
    //    BindingFlags bf = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance |
    //          BindingFlags.NonPublic;//反射标识
    //    PropertyInfo[] propInfos = data.GetType().GetProperties();//取出所有公共属性 
    //    foreach (PropertyInfo item in propInfos)
    //    {
    //        FieldInfo fiPage = pgType.GetField(item.Name, bf);//从页面中取出满足某一个属性的字段
    //        if (fiPage != null) //页面的字段不为空,代表存在一个实例化的控件类
    //        {
    //            object value = null;
    //            Control pgControl = (Control)fiPage.GetValue(this); //根据属性，找到页面对应控件，这要求页面控件命名必须和对象的属性一一对应相同

    //            //下面取值
    //            Type controlType = pgControl.GetType();
    //            if (controlType == typeof(Label))
    //            {
    //                value = ((Label)pgControl).Text.Trim();
    //            }
    //            else if (controlType == typeof(TextBox))
    //            {
    //                value = ((TextBox)pgControl).Text.Trim();
    //            }
    //            else if (controlType == typeof(HtmlInputText))
    //            {
    //                value = ((HtmlInputText)pgControl).Value.Trim();
    //            }
    //            else if (controlType == typeof(HiddenField))
    //            {
    //                value = ((HiddenField)pgControl).Value.Trim();
    //            }
    //            else if (controlType == typeof(CheckBox))
    //            {
    //                value = (((CheckBox)pgControl).Checked);//复选框
    //            }
    //            else if (controlType == typeof(DropDownList))//下拉框
    //            {
    //                value = ((DropDownList)pgControl).SelectedValue;
    //            }
    //            else if (controlType == typeof(RadioButtonList))//单选框列表
    //            {
    //                value = ((RadioButtonList)pgControl).SelectedValue;
    //                if (value != null)
    //                {
    //                    if (value.ToString().ToUpper() != "TRUE" && value.ToString().ToUpper() != "FALSE")
    //                        value = value.ToString() == "1" ? true : false;
    //                }

    //            }
    //            else if (controlType == typeof(Image)) //图片
    //            {
    //                value = ((Image)pgControl).ImageUrl;
    //            }
    //            try
    //            {
    //                object realValue = null;
    //                if (item.PropertyType.Equals(typeof(Nullable<DateTime>))) //泛型可空类型 
    //                {
    //                    if (value != null)
    //                    {
    //                        if (string.IsNullOrEmpty(value.ToString()))
    //                        {
    //                            realValue = null;
    //                        }
    //                        else
    //                        {
    //                            realValue = DateTime.Parse(value.ToString());
    //                        }
    //                    }
    //                }
    //                else if (item.PropertyType.Equals(typeof(Nullable))) //可空类型 
    //                {
    //                    realValue = value;
    //                }
    //                else
    //                {
    //                    try
    //                    {
    //                        realValue = Convert.ChangeType(value, item.PropertyType);
    //                    }
    //                    catch
    //                    {
    //                        realValue = null;
    //                    }
    //                }
    //                item.SetValue(data, realValue, null);
    //            }
    //            catch (FormatException fex)
    //            {
    //                DotNet.Common.Util.Logger.WriteFileLog(fex.Message,
    //                     HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");
    //                throw fex;
    //            }
    //            catch (Exception ex)
    //            {
    //                DotNet.Common.Util.Logger.WriteFileLog(ex.Message,
    //                    HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");
    //                throw ex;
    //            }
    //        }
    //    }
    //    return data;
    //}

    /////// <summary>
    /////// 通过对象的属性值，给页面控件赋值
    /////// </summary>
    /////// <param name="data"></param>
    //public virtual void SetFormData(BaseObj data)
    //{
    //    Type pgType = this.GetType();
    //    BindingFlags bf = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic |
    //         BindingFlags.Static;
    //    PropertyInfo[] propInfos = data.GetType().GetProperties();
    //    foreach (PropertyInfo item in propInfos)
    //    {
    //        FieldInfo myField = pgType.GetField(item.Name, bf);
    //        if (myField != null)
    //        {
    //            Control myControl = (Control)myField.GetValue(this); //根据属性名取到页面控件
    //            object value = item.GetValue(data, null); //取对象的属性值
    //            Type propType = item.PropertyType;

    //            if (value != null)
    //            {
    //                Type valueType = value.GetType();
    //                try
    //                {
    //                    Type controlType = myControl.GetType();
    //                    if (controlType == typeof(Label))
    //                    {
    //                        if (valueType == typeof(DateTime))
    //                        {
    //                            ((Label)myControl).Text = (Convert.ToDateTime(value)).ToShortDateString();
    //                        }
    //                        else
    //                        {
    //                            ((Label)myControl).Text = value.ToString();
    //                        }

    //                    }
    //                    else if (controlType == typeof(TextBox))
    //                    {
    //                        if (valueType == typeof(DateTime))
    //                        {
    //                            ((TextBox)myControl).Text = (Convert.ToDateTime(value)).ToShortDateString();
    //                        }
    //                        else
    //                        {
    //                            ((TextBox)myControl).Text = value.ToString();
    //                        }
    //                    }
    //                    else if (controlType == typeof(HtmlInputText))
    //                    {
    //                        if (valueType == typeof(DateTime))
    //                        {
    //                            ((HtmlInputText)myControl).Value = (Convert.ToDateTime(value)).ToShortDateString();
    //                        }
    //                        else
    //                        {
    //                            ((HtmlInputText)myControl).Value = value.ToString();
    //                        }
    //                    }
    //                    else if (controlType == typeof(HiddenField))
    //                    {
    //                        ((HiddenField)myControl).Value = value.ToString();
    //                    }
    //                    else if (controlType == typeof(CheckBox))
    //                    {
    //                        if (valueType == typeof(Boolean)) //布尔型
    //                        {
    //                            if (value.ToString().ToUpper() == "TRUE")
    //                                ((CheckBox)myControl).Checked = true;
    //                            else
    //                                ((CheckBox)myControl).Checked = false;
    //                        }
    //                        else if (valueType == typeof(Int32)) //整型 (正常情况下,1标识选择,0标识不选)
    //                        {
    //                            ((CheckBox)myControl).Checked = string.Compare(value.ToString(), "1") == 0;
    //                        }

    //                    }
    //                    else if (controlType == typeof(DropDownList))
    //                    {
    //                        try
    //                        {
    //                            ((DropDownList)myControl).SelectedValue = value.ToString();
    //                        }
    //                        catch
    //                        {
    //                            ((DropDownList)myControl).SelectedIndex = -1;
    //                        }
    //                    }
    //                    else if (controlType == typeof(RadioButton))
    //                    {
    //                        if (valueType == typeof(Boolean)) //布尔型
    //                        {
    //                            if (value.ToString().ToUpper() == "TRUE")
    //                                ((RadioButton)myControl).Checked = true;
    //                            else
    //                                ((RadioButton)myControl).Checked = false;
    //                        }
    //                        else if (valueType == typeof(Int32)) //整型 (正常情况下,1标识选择,0标识不选)
    //                        {
    //                            ((RadioButton)myControl).Checked = string.Compare(value.ToString(), "1") == 0;
    //                        }
    //                    }
    //                    else if (controlType == typeof(RadioButtonList))
    //                    {
    //                        try
    //                        {
    //                            if (valueType == typeof(Boolean)) //布尔型
    //                            {
    //                                if (value.ToString().ToUpper() == "TRUE")
    //                                    ((RadioButtonList)myControl).SelectedValue = "1";
    //                                else
    //                                    ((RadioButtonList)myControl).SelectedValue = "0";
    //                            }
    //                            else
    //                                ((RadioButtonList)myControl).SelectedValue = value.ToString();
    //                        }
    //                        catch
    //                        {
    //                            ((RadioButtonList)myControl).SelectedIndex = -1;
    //                        }

    //                    }
    //                    else if (controlType == typeof(Image))
    //                    {
    //                        ((Image)myControl).ImageUrl = value.ToString();
    //                    }
    //                }
    //                catch (FormatException fex)
    //                {
    //                    DotNet.Common.Util.Logger.WriteFileLog(fex.Message,
    //                        HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");
    //                }
    //                catch (Exception ex)
    //                {
    //                    DotNet.Common.Util.Logger.WriteFileLog(ex.Message,
    //                       HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");
    //                }
    //            }
    //        }
    //    }
    //}

    //#endregion

    #endregion


    #region 门店 品牌 城市 等.

    //获取省份名称
    protected string GetProvinceName(int id)
    {
        var info = BarberCommonBLL.GetProvinceById(id);
        return info.ProName;
    }
    //获取城市名称
    protected string GetCityName(int id, int proId)
    {
        var info = BarberCommonBLL.GetCityById(id, proId);
        return info.CityName;
    }
    //获取品牌名称
    protected string GetBrandName(int id)
    {
        var info = BrandInfoBLL.GetBrandById(id);
        return info.BrandName;
    }
    //获取们店名称
    protected string GetStoresName(int id)
    {
        var info = StoresInfoBLL.GetStoresInfo(id);
        return info.StoreName;
    }
    //获取门店设备数量
    protected string GetStoresDevicemNum(int id, int status)
    {
        var num = BarberCommonBLL.GetDeviceNumByStoreId(id, status);
        return num.ToString();
    }

    //获取品牌设备数量
    protected string GetBrandDevicemNum(int id, int status)
    {
        var num = BarberCommonBLL.GetDeviceNumByBrandId(id, status);
        return num.ToString();
    }
    #endregion

    #region 上传图片
    /// <summary>
    /// asp.net上传图片并生成缩略图
    /// </summary>
    /// <param name="upImage">HtmlInputFile控件</param>
    /// <param name="sSavePath">保存的路径,些为相对服务器路径的下的文件夹</param>
    /// <param name="sThumbExtension">缩略图的thumb</param>
    /// <param name="intThumbWidth">生成缩略图的宽度</param>
    /// <param name="intThumbHeight">生成缩略图的高度</param>
    /// <returns>缩略图名称</returns>
    public string UpLoadImage(HtmlInputFile upImage, string sSavePath, string sThumbExtension, int intThumbWidth, int intThumbHeight, out string sFilename, out string sThumbFile)
    {
        //string sThumbFile = "";
        //string sFilename = "";
        sThumbFile = "";
        sFilename = "";
        if (upImage.PostedFile != null)
        {
            HttpPostedFile myFile = upImage.PostedFile;
            int nFileLen = myFile.ContentLength;
            if (nFileLen == 0)
                return "没有选择上传图片";
            //获取upImage选择文件的扩展名
            string extendName = System.IO.Path.GetExtension(myFile.FileName).ToLower();
            //判断是否为图片格式
            if (extendName != ".jpg" && extendName != ".jpge" && extendName != ".gif" && extendName != ".bmp" && extendName != ".png")
                return "图片格式不正确";

            byte[] myData = new Byte[nFileLen];
            myFile.InputStream.Read(myData, 0, nFileLen);
            //sFilename = System.IO.Path.GetFileName(myFile.FileName);
            //int file_append = 0;
            ////检查当前文件夹下是否有同名图片,有则在文件名+1
            //while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename)))
            //{
            //    file_append++;
            //    sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
            //        + file_append.ToString() + extendName;
            //}
            sFilename = UploadUtil.mikecat_GetNumberRandom() + extendName;
            //没则创建
            //if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath)))
            //{
            //    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(sSavePath));
            //}
            if (!Directory.Exists(sSavePath))
            {
                Directory.CreateDirectory(sSavePath);
            }
            System.IO.FileStream newFile
                = new System.IO.FileStream(sSavePath + sFilename,
                System.IO.FileMode.Create, System.IO.FileAccess.Write);
            newFile.Write(myData, 0, myData.Length);
            newFile.Close();
            //以上为上传原图
            try
            {
                //原图加载
                using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(sSavePath + sFilename))
                {
                    //原图宽度和高度
                    int width = sourceImage.Width;
                    int height = sourceImage.Height;
                    int smallWidth;
                    int smallHeight;
                    //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽 和 原图的高/缩略图的高)
                    if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight)
                    {
                        smallWidth = intThumbWidth;
                        smallHeight = intThumbWidth * height / width;
                    }
                    else
                    {
                        smallWidth = intThumbHeight * width / height;
                        smallHeight = intThumbHeight;
                    }
                    ////判断缩略图在当前文件夹下是否同名称文件存在
                    //file_append = 0;
                    //sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + extendName;
                    sThumbFile = System.IO.Path.GetFileNameWithoutExtension(sFilename) + sThumbExtension + extendName;
                    //while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sThumbFile)))
                    //{
                    //    file_append++;
                    //    sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
                    //        file_append.ToString() + extendName;
                    //}
                    //缩略图保存的绝对路径
                    //string smallImagePath = System.Web.HttpContext.Current.Server.MapPath(sSavePath) + sThumbFile;
                    string smallImagePath = sSavePath + sThumbFile;
                    //新建一个图板,以最小等比例压缩大小绘制原图
                    using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight))
                    {
                        //绘制中间图
                        using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
                        {
                            //高清,平滑
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.Clear(Color.Black);
                            g.DrawImage(
                            sourceImage,
                            new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight),
                            new System.Drawing.Rectangle(0, 0, width, height),
                            System.Drawing.GraphicsUnit.Pixel
                            );
                        }
                        //新建一个图板,以缩略图大小绘制中间图
                        using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight))
                        {
                            //绘制缩略图
                            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1))
                            {
                                //高清,平滑
                                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                g.Clear(Color.Black);
                                int lwidth = (smallWidth - intThumbWidth) / 2;
                                int bheight = (smallHeight - intThumbHeight) / 2;
                                g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel);
                                g.Dispose();
                                bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                            }
                        }
                    }
                }
            }
            catch
            {
                //出错则删除
                //System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename));
                System.IO.File.Delete(sSavePath + sFilename);
                return "图片格式不正确";
            }
            //返回缩略图名称
            return "";
        }
        return "没有选择图片";
    }
    #endregion


}
